﻿using FC.Data.ViewModels.Account;
using FC.Data.ViewModels.Contests;
using FC.IService;
using FC.Service;
using FC.Utils;
using FC.Web.Fillters;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace FC.Web.Controllers
{
    [LoginFillter]
    public class ManagerController : Controller
    {
        /// <summary>
        /// 试题集服务
        /// </summary>
        IContestsService contestsService = new ContestsService();

        /// <summary>
        /// 公共信息服务
        /// </summary>
        IPublicService publicService = new PublicService();

        // GET: Manager
        public ActionResult Index()
        {
            return View();
        }

        #region 试题集管理

        /// <summary>
        /// 试题管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Contests()
        {
            var list = contestsService.GetCollections();
            return View(list);
        }
        
        /// <summary>
        /// 添加/编辑试题集
        /// </summary>
        /// <param name="first">试题集编号</param>
        /// <returns></returns>
        public ActionResult EditContest(string first)
        {
            ViewBag.Title = "添加试题集";
            ProblemCollection model = null;
            if (!string.IsNullOrWhiteSpace(first))
            {
                ViewBag.Title = "编辑试题集";
                model = contestsService.GetCollection(first);
            }
            return View(model);
        }

        /// <summary>
        /// 编辑试题集表单提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult SaveContest(ProblemCollection model)
        {
            var r = contestsService.SaveCollection(model);
            return Json(r);
        }

        /// <summary>
        /// 删除试题集
        /// </summary>
        /// <param name="first">试题集编号</param>
        /// <returns></returns>
        public JsonResult DeleteContest(string first)
        {
            Result result = contestsService.DeleteContest(first);
            return Json(result);
        }

        /// <summary>
        /// 题目管理
        /// </summary>
        /// <param name="first">试题集编号</param>
        /// <returns></returns>
        public ActionResult Problems(string first, int? page)
        {
            ViewBag.Collection = first;
            var model = contestsService.GetProblemList(first, page??1);
            return View(model);
        }

        /// <summary>
        /// 添加/编辑题目
        /// </summary>
        /// <param name="first">试题集编号</param>
        /// <param name="second">题目Id</param>
        /// <returns></returns>
        public ActionResult EditProblem(string first, int? second)
        {
            ViewBag.Collection = first;
            ProblemContent model = null;
            if (second != null && second != 0)
            {
                ViewBag.Title = "编辑题目";
                model = contestsService.GetProblemContent(first, second ?? 0);
            }
            else
            {
                ViewBag.Title = "添加题目";
                model = new ProblemContent()
                {
                    Author = (Session["User"] as User).UserName,
                    TestProcedure = "Standard",
                    CodeLengthRestriction = 8000,
                    MemoryLimit = 65536,
                    TimeLimit = 1000,
                    CollectionCode = first,
                };
            }
            if(model.Examples == null || model.Examples.Count == 0)
            {
                model.Examples = new List<ProblemExample>()
                {
                    new ProblemExample()
                };
            }
            return View(model);
        }

        /// <summary>
        /// 添加/编辑题目表单提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult SaveProblem(ProblemContent model)
        {
            Result r = contestsService.SaveProblem(model);
            return Json(r);
        }

        /// <summary>
        /// 删除试题集
        /// </summary>
        /// <param name="first">试题集编号</param>
        /// <param name="second">题目Id</param>
        /// <returns></returns>
        public JsonResult DeleteProblem(string first, int? second)
        {
            Result result = contestsService.DeleteProblem(first, second);
            return Json(result);
        }

        /// <summary>
        /// 清空试题集
        /// </summary>
        /// <param name="first"></param>
        /// <returns></returns>
        public JsonResult ClearCollection(string first)
        {
            Result result = contestsService.ClearCollection(first);
            return Json(result);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="first"></param>
        public void Export(string first)
        {
            IWorkbook workbook = contestsService.Export(first);

            if (workbook != null)
            {
                //设置响应的类型为Excel
                Response.ContentType = "application/vnd.ms-excel";
                //设置下载的Excel文件名
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "test.xls"));
                //Clear方法删除所有缓存中的HTML输出。但此方法只删除Response显示输入信息，不删除Response头信息。以免影响导出数据的完整性。
                Response.Clear();

                using (MemoryStream ms = new MemoryStream())
                {
                    //将工作簿的内容放到内存流中
                    workbook.Write(ms);
                    //将内存流转换成字节数组发送到客户端
                    Response.BinaryWrite(ms.GetBuffer());
                    Response.End();
                }
            }
        }

        /// <summary>
        /// 批量导入页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Import()
        {
            return View();
        }

        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Import(HttpPostedFileBase file)
        {
            var result = contestsService.Import(file);
            return Json(result);
        }

        /// <summary>
        /// 从网站导入
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportFromWeb(string first)
        {
            return View();
        }

        #endregion

        #region 公共信息（行政区划及天气代码） 信息管理
        /// <summary>
        /// 管理主界面
        /// </summary>
        /// <returns></returns>
        public ActionResult PublicInfo()
        {
            return View();
        }

        /// <summary>
        /// 导入天气代码界面
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportWeatherCode()
        {
            return View();
        }

        /// <summary>
        /// 导入文件接收
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ImportWeatherCode(HttpPostedFileBase file)
        {
            IWorkbook workbook;
            var result = publicService.ImportWeatherCode(file, out workbook);

            if (Session["Workbook"] == null)
                Session.Add("Workbook", workbook);
            else Session["Workbook"] = workbook;

            return Json(result);
        }

        public void DownloadImportResult()
        {
            IWorkbook workbook = Session["Workbook"] as IWorkbook;

            if (workbook != null)
            {
                //设置响应的类型为Excel
                Response.ContentType = "application/vnd.ms-excel";
                //设置下载的Excel文件名
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "ImportResult.xls"));
                //Clear方法删除所有缓存中的HTML输出。但此方法只删除Response显示输入信息，不删除Response头信息。以免影响导出数据的完整性。
                Response.Clear();

                using (MemoryStream ms = new MemoryStream())
                {
                    //将工作簿的内容放到内存流中
                    workbook.Write(ms);
                    //将内存流转换成字节数组发送到客户端
                    Response.BinaryWrite(ms.GetBuffer());
                    Response.End();
                }
            }
        }

        public void DownloadPublicInfo()
        {
            IWorkbook workbook = publicService.GetPublicInfo();

            if (workbook != null)
            {
                //设置响应的类型为Excel
                Response.ContentType = "application/vnd.ms-excel";
                //设置下载的Excel文件名
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "ImportResult.xls"));
                //Clear方法删除所有缓存中的HTML输出。但此方法只删除Response显示输入信息，不删除Response头信息。以免影响导出数据的完整性。
                Response.Clear();

                using (MemoryStream ms = new MemoryStream())
                {
                    //将工作簿的内容放到内存流中
                    workbook.Write(ms);
                    //将内存流转换成字节数组发送到客户端
                    Response.BinaryWrite(ms.GetBuffer());
                    Response.End();
                }
            }
        }

        #endregion

        #region 论坛管理

        /// <summary>
        /// 论坛管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Bolg()
        {
            return View();
        }

        #endregion
    }
}